<?php
namespace app\admin\controller;
use app\admin\model\Patient as thisModel;
use app\admin\model\Equipgroup as equipgroupModel;
use app\home\model\Api as apiModel;
use think\Db;
use Env;
use PHPExcel_IOFactory;
class Patient extends Common
{
    function index(){
        $thisModel = new thisModel();
        $equipgroupModel = new equipgroupModel();
        $mainData = $thisModel->mainData();
        $inputData = input('get.');

        // 分组
        $equipgroup_list = $equipgroupModel->mainAllList();
        $this->assign('equipgroup_list', $equipgroup_list);

     // dump($mainData);exit;
        $this->assign('list',$mainData['list']);
        $this->assign('page',$mainData['page']);
        $this->assign('count',$mainData['count']);
        $this->assign('inputData',$inputData);

        return $this->fetch('index');
    }

    function warning_handle(){
        $apiModel = new apiModel();
        if(input('patient_id') > 0){
            $patient = Db::name('patient')->where(array('patient_id'=>input('patient_id')))->find();
            if($patient){
                Db::name('patient')->where(array('id'=>$patient['id']))->update(array('iswarn_today'=>0));
                $delWhere = "xinpian='".$patient['rfid']."' AND createtime>".strtotime(date("Ymd"));
                Db::name('sign_record')->where($delWhere)->delete();
            }
            /*$data = array(
                'patient_id' => input('patient_id'),
                );
            $res = $apiModel->warning_handle($data);
            
            echo json_encode($res);exit;*/
        }
    }

    function tongbu(){
        $this->redirect('home/Api/test');exit;
    }

    //编辑
    function mainEdit()
    {
        $thisModel = new thisModel();
        
        if (request()->isAjax()) {
            // (new \app\admin\validate\User()) -> goCheck();
            $data = $thisModel->disposeData(input('post.'));
            $id = input('post.id');
         // dump(input('post.'));
            if($id > 0){
                $data['updatetime'] = time();
                $res = Db::name('patient')->where("id",$id)->update($data);
                if ($res !== false) {
                    exitjson(1, '保存成功');
                } else {
                    exitjson(0, '保存失败');
                }
            }else{
                $patient = Db::name('patient')->where('patient_id',input('post.patient_id'))->find();
                if($patient){
                    exitjson(0, '病人记账号已存在');
                }else{
                    $res = Db::name('patient')->insertGetId($data);
                    if ($res) {
                        exitjson(1, '保存成功');
                    } else {
                        exitjson(0, '保存失败');
                    }
                }
            }

        } else {
            

            if(input('id') > 0){
                $one = Db::name('patient')->find(input('id'));
                $this->assign('one',$one);
            }
//            dump($one);exit;
            return $this->fetch('mainEdit');
        }
    }

    function mainDel(){
        $id = input('id');
        if($id>0){
            $res = Db::name('patient')->where("id",$id)->delete();
            if($res !== false){
                exitjson('1','删除成功');
            }else{
                exitjson(0,'删除失败');
            }
        }
    }

    //导入表格
    public function importExcel(){
        header("content-type:text/html;charset=utf-8");
        if (empty ($_FILES ['excelfile'] ['name'])){
            exitjson(0,'请选择文件');
        }
        $file_types = explode(".", $_FILES ['excelfile'] ['name']);
        $file_type = $file_types [count($file_types) - 1];
        // dump($file_type);
        /*判别是不是.xls文件，判别是不是excel文件*/
        if (strtolower($file_type) != "xlsx" && strtolower($file_type) !="xls") {
            // $this->error('不是Excel文件，重新上传');
            exitjson(0,'不是Excel文件，重新上传');
        }
        //上传excel文件
        $file = request()->file('excelfile');
        //将文件保存到public/uploads目录下面
        $info = $file->validate(['size'=>1048576,'ext'=>'xls,xlsx'])->move( 'userfiles/files/');
        if($info){
            //获取上传到后台的文件名
            $fileName = $info->getSaveName();
            //获取文件路径
            $filePath = Env::get('root_path').'userfiles'.DIRECTORY_SEPARATOR.'files'.DIRECTORY_SEPARATOR.$fileName;
            //获取文件后缀
            $suffix = $info->getExtension();
            //判断哪种类型
            if($suffix=="xlsx"){
                $reader = \PHPExcel_IOFactory::createReader('Excel2007');
                }else{
                $reader = PHPExcel_IOFactory::createReader('Excel5'); 
                }
            }else{
                // $this->error('文件过大或格式不正确导致上传失败-_-!');
                exitjson(0,'文件过大或格式不正确导致上传失败-_-!');
            }
        //载入excel文件
        $excel = $reader->load("$filePath",$encode = 'utf-8');
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        //获取总列数
        $col_num = $sheet->getHighestColumn();
        $data = []; //数组形式获取表格数据
        for ($i=2; $i <=$row_num; $i++) { 
            $artType = $sheet->getCell("A".$i)->getValue();
            if($artType=='理科' || $artType==2){
                $art_type = 2;
            }else{
                $art_type = 1;
            }
            $data[$i]['art_type']   = $art_type;
            $data[$i]['user_name'] = $sheet->getCell("B".$i)->getValue();
            $data[$i]['pwd']     = $excel->getActiveSheet()->getCell("C".$i)->getValue();
            $data[$i]['password'] = encrypt($data[$i]['pwd']);
            $data[$i]['nick_name']     = $excel->getActiveSheet()->getCell("D".$i)->getValue();
            $data[$i]['sex'] = $sheet->getCell("E".$i)->getValue();
            $data[$i]['add_time'] = time();
            $data[$i]['is_del'] = 0;
            //将数据保存到数据库
            $user = Db::name('user')->where('user_name',$data[$i]['user_name'])->find();
            if($user){
                $username = $data[$i]['user_name'];
                unset($data[$i]['user_name']);
                Db::name('user')->where('user_name',$username)->update($data[$i]);
                unset($data[$i]);  //如果学员账号存在，unset掉
            }
        }
        // dump($data);exit;
        $res = Db::name('user')->insertAll($data);
        if($res){
//          unlink($filePath);
            exitjson(1,'导入成功');
        }else{
            exitjson(0,'导入失败');
        }

    }
















}